package com.example.lancooznbk.presenter;

import android.util.Log;

import com.example.lancooznbk.MyApplication;
import com.example.lancooznbk.model.api.LearnTypeApi;
import com.example.lancooznbk.model.api.ServerAddressApi;
import com.example.lancooznbk.model.result.LearnTypeEntity;
import com.example.lancooznbk.model.result.ServerAddressBeanXml;
import com.example.lancooznbk.model.result.ServerAddressEntityXml;
import com.example.lancooznbk.presenter.presenter_interface.ISplashPresenter;
import com.example.lancooznbk.view.view_interface.ISplashView;
import com.lancoo.cpbase.authentication.base.AddressOperater;
import com.lancoo.dictionary.DictionaryHelper;
import com.lancoo.reviewsystem.utils.ToastUtils;
import com.lancoo.rxretrofitlibrary.http.HttpManager;
import com.lancoo.rxretrofitlibrary.http.RetrofitUrlManager;
import com.lancoo.rxretrofitlibrary.listener.HttpOnNextListener;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;

import znbkTestPaperInfor.ZnbkPaperInfor;

import static com.lancoo.rxretrofitlibrary.http.RetrofitUrlManager.API_DOMAIN_NAME;
import static com.lancoo.rxretrofitlibrary.http.RetrofitUrlManager.RESOURCE_DOMAIN_NAME;

/**
 * Created by tangminglong on 17/7/26.
 */

public class SplashPresenter implements ISplashPresenter {

    private ISplashView mMainView;


    private String strBaseAddress;

    //调用webservice接口的名称空间
    private static final String NAMESPACE = "http://LGCPWS_Basic.org/";
    private static final String METHOD_NAME = "WS_G_GetSubSystemServerInfo";
    private static String SOAP_ACTION = NAMESPACE + METHOD_NAME;


    public SplashPresenter(ISplashView mMainView) {
        this.mMainView = mMainView;

    }

    @Override
    public void getData() {

        AddressOperater mAddress = new AddressOperater(mMainView.getHolderActivity());
        String address = mAddress.getBaseAddress();
        strBaseAddress = address;
        Log.e("getData()","getData()");


        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    SoapObject soapChildrenData = null;
                    SoapObject soapAddress = null;
                    soapAddress = getAddress("P10","S2-English");
                    soapChildrenData = (SoapObject) soapAddress.getProperty(0);
                    String httpAddressData = soapChildrenData.getProperty(3).toString();
//                    String httpAddressData = "http://172.16.41.235:2020/";
                    ZnbkPaperInfor.BaseHttpAdress = httpAddressData;
//                  String httpAddressData = "http://172.16.41.235:2017/";
                    Log.e("httpAddressData","httpAddressData+"+httpAddressData);
                    //设置默认的基础地址
                    RetrofitUrlManager.getInstance().putDomain(API_DOMAIN_NAME,httpAddressData);
                    RetrofitUrlManager.getInstance().setGlobalDomain(httpAddressData);
                    //BaseApi.setAppDefaultDomain(httpAddressData);//存储基础地址

                /*
                * 获取音频，图片资源地址
                * */

                soapAddress = getAddress("A00","S2-English");
                SoapObject soapChildrenResource = (SoapObject) soapAddress.getProperty(0);
                String httpAddressResource = soapChildrenResource.getProperty(3).toString();

                    //初始化电子词典插件
                DictionaryHelper.install(mMainView.getHolderActivity().getApplication());
                DictionaryHelper.setUp(RetrofitUrlManager.getInstance().fetchDomainStr(API_DOMAIN_NAME)+"/api/ZNBK/W_ZNBK_GetCourseWare","");

                getBaseResAddress(httpAddressResource);


                    //初始化所有题型
//                getAllLearnType();

                } catch (Exception e) {
                    e.printStackTrace();
                }

                //跳转
                mMainView.goMainActivity(true);

            }
        }).start();

    }



    private void getAllLearnType(){
        HttpOnNextListener<List<LearnTypeEntity>> httpOnNextListener = new HttpOnNextListener<List<LearnTypeEntity>>() {
            @Override
            public void onNext(List<LearnTypeEntity> learnTypeEntities) {
                ((MyApplication)mMainView.getHolderActivity().getApplication()).setLearnTypeEntities(learnTypeEntities);
                Log.e("getAllLearnType","true");
                //跳转
                mMainView.goMainActivity(true);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.showShort("数据初始化失败，请配置有效地址");
                Log.e("getAllLearnType","false");
                mMainView.goMainActivity(false);

            }
        };

        LearnTypeApi api = new LearnTypeApi(httpOnNextListener,mMainView.getHolderActivity());
        HttpManager.getInstance().doHttpDeal(api);
    }

    /**
     *获取系统服务信息
     * @param sysID 系统ID sysID = P10 获取智能备考系统的基础地址  sysID = A00 获取到智能备考系统资源的基础地址
     * @param subjectID 学科ID
     * @return
     */
    private SoapObject getAddress(String sysID, String subjectID) {
        try {

            SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
            //设置需要返回请求对象的参数
            rpc.addProperty("sysID", sysID);
            rpc.addProperty("subjectID", subjectID);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.bodyOut = rpc;
            envelope.dotNet = true;
            envelope.setOutputSoapObject(rpc);

            HttpTransportSE ht = new HttpTransportSE(strBaseAddress + "Base/WS/Service_Basic.asmx");

            ht.debug = true;

            ht.call(SOAP_ACTION, envelope);

            if (envelope.getResponse() != null) {
                // 获取服务器响应返回的SOAP消息
                SoapObject result = (SoapObject) envelope.bodyIn;
                // 解析服务器响应的SOAP消息
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取资源服务器的基础地址 Http
     * @param baseUrl 接口访问的基础地址
     */
    private void getBaseResAddress(String baseUrl){
        HttpOnNextListener httpOnNextListener = new HttpOnNextListener<ServerAddressEntityXml>() {
            @Override
            public void onNext(ServerAddressEntityXml resAddressEntityXml) {
                int listSize = resAddressEntityXml.getList().size();
                for (int i = 0; i < listSize; i++) {
                    ServerAddressBeanXml resAddr = resAddressEntityXml.getList().get(i);
                    if ("HTTP资源服务器".equals(resAddr.getServerName())){
                        //获取成功，将IP地址信息写入本地文件
                        String urlRes = "http://" + resAddr.getIp() + ":" + resAddr.getPort();
                        Log.e("getBaseResAddress","urlRes+"+urlRes);
                        RetrofitUrlManager.getInstance().putDomain(RESOURCE_DOMAIN_NAME,urlRes);
                        //mMainView.goMainActivity();
                        break;

                    }
                }
            }
        };

        ServerAddressApi serverAddressApi = new ServerAddressApi(httpOnNextListener,mMainView.getHolderActivity());
        RetrofitUrlManager.getInstance().putDomain(RetrofitUrlManager.SERVER_ADDRESS_NAME,baseUrl);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpXmlDeal(serverAddressApi);
    }
}
